package com.ifdom.thread.threadpool;

import java.util.concurrent.*;

/**
 * 自定义线程池构造器
 * 自定义构造器可以设置线程名称以及优先级
 *
 * @Author ifredomvip@gmail.com
 * @Date 2022/10/4 16:55
 * @Version 1.0.0
 * @Description
 **/
public class DefineCallerRunsPolicy {
    public static void main(String[] args) {

        ExecutorService executorService = new ThreadPoolExecutor(1,
                2,
                300,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy() {

                    void beforeExecute(Thread t, Runnable r) {
                        System.out.println("准备执行：beforeExecute");
                    }

                    void afterExecute(Runnable r, Throwable t) {
                        System.out.println("执行完毕：afterExecute");
                    }

                    void terminated() {
                        System.out.println("线程池退出");
                    }
                }
        );


        Runnable task = () -> {
            try {
                Thread.sleep(3000);
                System.out.println("执行任务");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        for (int i = 0; i < 8; i++) {
            executorService.execute(task);
        }

        executorService.shutdown();
    }
}
